import cv2
import numpy as np


# 调节公式: g(x)=αf(x)+β
class MyImageEditor:
    def __init__(self, path):
        self._contrastRatio = 0.3   # 对比度
        self._brightness = 80   # 亮度
        self._saturation = 10   # 饱和度
        self._path = path   # 图片路径
        self._img = cv2.imread(self._path)
        self._img2 = cv2.imread(self._path)

    @property
    def img(self):
        return self._img

    # 调节图片对比度(通过contrastRatio属性, 一般在0-3.0之间, 所以滑动条范围设为0-300)
    def _updateContrastRatio(self, x):
        self._contrastRatio = cv2.getTrackbarPos('Contrast', 'image')
        self._contrastRatio = self._contrastRatio * 0.01
        # np.clip()防止像素值越界
        self._img = np.uint8(np.clip((self._contrastRatio * self._img2 + self._brightness), 0, 255))

    # 调节图片亮度(通过brightness属性)
    def _updateBrightness(self, x):
        self._brightness = cv2.getTrackbarPos('Brightness', 'image')
        self._img = np.uint8(np.clip((self._contrastRatio * self._img2 + self._brightness), 0, 255))

    # 创建窗口
    def createWindow(self):
        cv2.namedWindow('image')
        cv2.createTrackbar('Contrast', 'image', 0, 300, self._updateContrastRatio)
        cv2.createTrackbar('Brightness', 'image', 0, 255, self._updateBrightness)
        cv2.setTrackbarPos('Contrast', 'image', 100)
        cv2.setTrackbarPos('Brightness', 'image', 10)

    @staticmethod
    def destroy():
        cv2.destroyAllWindows()


if __name__ == '__main__':
    my_image_editor = MyImageEditor("D:\\download\\450d23eaec784b8d19f413014b020f3b.jpeg")
    my_image_editor.createWindow()
    while True:
        cv2.imshow('image', my_image_editor.img)
        if cv2.waitKey(1) == ord('q'):
            break
    MyImageEditor.destroy()
